package com.jims.api.v1.controller.weixin.doctor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.my.controller.BaseController;
import com.jims.master.common.data.Message;
import com.jims.master.common.utils.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 医生微信公众基本配置验证Controller
 * @author WangYq
 * @version 2018-01-22
 */
@Controller
@RequestMapping(value="wx")
public class WX_Controller extends BaseController{

    private static Logger log = LoggerFactory.getLogger(WX_Controller.class);
    /**
     * @Title: getWeiXinMethod
     * @Description: （微信公众号基本配置的验证）
     * @param
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-01-24
     * @throws
     */
    @RequestMapping(value="getWeiXinMethod",method= RequestMethod.GET)
    @ResponseBody
    public void getWeiXinMethod(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = response.getWriter();
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
        out.close();
        out = null;
    }
    /**
     * @Title: getAccessToken
     * @Description: （获取微型公众号的access_token）
     * @param
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-01-24
     * @throws
     */
    @RequestMapping(value="getAccessToken",method=RequestMethod.GET)
    @ResponseBody
    public String getAccessToken(HttpServletRequest request, HttpServletResponse response){
        Message msg=new Message();
        msg.setData(WX_TokenUtil.getAccessToken());
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: getOpenidV100
     * @Description: （获取openid）
     * @param code
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-01-24
     * @throws
     */
    @RequestMapping(value = "V100/getOpenid",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String callBackUrl(HttpServletRequest req, HttpServletResponse resp,String code,String state) throws IOException {
        Message msg=new Message();
        /*String code=req.getParameter("code");*/
        Map<String, String> mapOpenid=null;
        Map<String, String> map=null;
        mapOpenid= WX_UserUtil.getUserInfoAccessToken(code);
//        map=WX_UserUtil.getUnionid(mapOpenid.get("openid"));
//        String openid=map.get("unionid");
        String docOpenid=mapOpenid.get("openid");
        Map<String, String> infoMap=new HashMap<String, String>();
        infoMap.put("openid",docOpenid);
        infoMap.put("state",state);
        infoMap.put("docOpenid",docOpenid);
        msg.setData(infoMap);
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: sendMessageV100
     * @Description: （发送消息）
     * @param
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-01-25
     * @throws
     */
    @RequestMapping(value = "V100/sendMessage",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String sendMessage(String code,HttpServletRequest req, HttpServletResponse resp) {
        Message msg=new Message();
        Map<String, String> map=WX_UserUtil.getUserInfoAccessToken(code);
        String openid=map.get("openid");
        String mes=senMsg(openid);
        if(mes.equals("success")){
            msg.setData("发送成功");
        }else {
            msg.setData("发送失败");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    public static String senMsg(String openId) {
        //用户是否订阅该公众号标识 (0代表此用户没有关注该公众号 1表示关注了该公众号)
        Integer state = WX_UserUtil.subscribeState(openId);
        log.info("是否订阅公众号state:" + state);
        // 绑定了微信并且关注了服务号的用户 , 注册成功-推送注册短信
        if (state == 1) {
            Map<String, TemplateData> param = new HashMap<>();
            param.put("first", new TemplateData("恭喜其小林！", "#696969"));
            param.put("keyword1", new TemplateData("12345345456", "#696969"));
            param.put("keyword2", new TemplateData("2017年", "#696969"));
            param.put("keyword3", new TemplateData("2017年", "#696969"));
            param.put("keyword4", new TemplateData("2017年", "#696969"));
            param.put("remark", new TemplateData("祝愉快！", "#696969"));
            //注册的微信-模板Id
            // String regTempId =  WX_TemplateMsgUtil.getWXTemplateMsgId("ywBb70467vr18");

            JSON.toJSONString(param);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(param));
            //调用发送微信消息给用户的接口
            return WX_TemplateMsgUtil.sendWechatMsgToUser(openId, "b9uT47wIcwrOKHSTG4he486PX5yISX3l-CHhoBFaPbE", "",
                    "#000000", jsonObject);


            /*//获取公众号的自动回复规则
            String urlinfo="https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token="+WX_TokenUtil.getWXToken().getAccessToken();
            JSONObject joinfo = WX_HttpsUtil.httpsRequest(urlinfo, "GET", null);
            Object o=joinfo.get("is_add_friend_reply_open");
            // System.out.println("o:"+joinfo);
            String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
            JSONObject Token = WX_HttpsUtil.httpsRequest(getTokenUrl, "GET", null);
            System.out.println("Token:"+Token);*/
        }
        return "error";
    }
}
